<?php

namespace app\merchant\controller;

use app\merchant\model\BorrowRequest;
use app\merchant\model\TpBorrower;
use app\merchant\model\TpCredit;
use app\merchant\service\MerchantService;
use app\common\lib\Page;
use app\merchant\model\UserMoneyLog;
use app\merchant\model\User;
use app\merchant\model\UserCompany;
use app\merchant\model\TpMerchant;
use app\merchant\model\MerchantConfig;
use app\merchant\model\BankCard;
use app\common\lib\Constant;
use app\common\lib\MyController;
use app\merchant\service\UserService;
use think\Db;
use think\Request;

/**
 * 商户基础信息
 */
class Merchant extends MyController
{

    /**
     * 商户信息概览
     * @return type
     */
    public function index()
    {
        $total = $this->_Account['balance'] + $this->_Account['freeze'];

        $today = Date('Y-m-d', time());
        $tomorrow = Date('Y-m-d', strtotime("+1 days"));
        $after_tomorrow = Date('Y-m-d', strtotime("+2 days"));

        $today = MerchantService::repayment_day($this->_Uid, $today);
        $tomorrow = MerchantService::repayment_day($this->_Uid, $tomorrow);
        $after_tomorrow = MerchantService::repayment_day($this->_Uid, $after_tomorrow);



        $repay_diff = round($today, 2) - round($total, 2);



        $start = strtotime(Date('Y-m-d', time()) . ' 00:00:00');
        $end = strtotime(Date('Y-m-d', time()) . ' 23:59:59');

        $map = [];
        $map['create_time'] = ['BETWEEN', [$start, $end]];
        $map['merchant'] = $this->_Uid;
        $today_request = BorrowRequest::where($map)->count();

        $map['status'] = 2;
        $today_request_failed = BorrowRequest::where($map)->count();

        $this->assign("today_request", $today_request);
        $this->assign("today_request_failed", $today_request_failed);


        $collect_today = Db::table('tp_credit')->alias('c')
                ->join('tp_assets_pool p', 'p.id=c.assets_pool_id')
                ->join('tp_borrow b', 'b.id=c.borrow_id')
                ->where('p.merchant', '=', $this->_Uid)
                ->where('b.recheck_time', '>', $start)
                ->sum('c.money');

        $this->assign("repay_diff", $repay_diff);
        $this->assign("repay_today", $today);
        $this->assign("repay_tomorrow", $tomorrow);
        $this->assign("repay_after_tomorrow", $after_tomorrow);
        $this->assign("collect_today", round($collect_today, 2));

        //查询项目数量
        $map = [];
        $map['b.planned_repay_time'] = ['BETWEEN', [$start, $end]];
        $map['p.merchant'] = $this->_Uid;
        $todaycount = Db::table('tp_credit')->alias('c')
                        ->join('tp_assets_pool p', 'c.assets_pool_id=p.id')
                        ->join('tp_borrow_repay b', 'c.borrow_id=b.borrow_id')
                        ->where($map)->group('c.id')->count();

        $start = strtotime(Date('Y-m-d', strtotime('+ 1 day')) . ' 00:00:00');
        $end = strtotime(Date('Y-m-d', strtotime('+ 1 day')) . ' 23:59:59');
        $map['b.planned_repay_time'] = ['BETWEEN', [$start, $end]];
        $tomorrowcount = Db::table('tp_credit')->alias('c')
                        ->join('tp_assets_pool p', 'c.assets_pool_id=p.id')
                        ->join('tp_borrow_repay b', 'c.borrow_id=b.borrow_id')
                        ->where($map)->group('c.id')->count();

        $this->assign("todaycount", $todaycount);
        $this->assign("tomorrowcount", $tomorrowcount);

        //待审核资产
        $assets_wait_check = Db::table('tp_assets_pool')
                        ->where('status', 0)
                        ->where('merchant', $this->_Uid)->count();

        $this->assign("assets_wait_check", $assets_wait_check);

        //待募集资产
        $assets_wait_sales = Db::table('tp_assets_pool')
                 ->where('status', 1)
                 ->where('merchant', $this->_Uid)->count();

        $this->assign("assets_wait_sales", $assets_wait_sales);





        return view('Merchant/index');
    }

    /**
     * 商户信息详情
     * @return type
     */
    public function show()
    {
        $user_id = $this->_Uid;

        //审核通过时间
        $merchant = TpMerchant::where('user_id', '=', $user_id)->find();
        $merchant['bond'] = number_format($merchant['bond'], 2);
        //商户配置        
        $car = $consume = $other = 0;
        $show_type = $merchant['show_type'];
        $types = explode(',', $show_type);
        if (in_array(MerchantConfig::CATEGORY_CAR, $types)) {
            $car = MerchantConfig::getInterestRateTermByCategory($user_id, MerchantConfig::CATEGORY_CAR);
        }
        if (in_array(MerchantConfig::CATEGORY_CONSUME, $types)) {
            $consume = MerchantConfig::getInterestRateTermByCategory($user_id, MerchantConfig::CATEGORY_CONSUME);
        }
        if (in_array(MerchantConfig::CATEGORY_COMPANY, $types)) {
            $other = MerchantConfig::getInterestRateTermByCategory($user_id, MerchantConfig::CATEGORY_COMPANY);
        }

        //用户信息
        $user = User::where('uid', '=', $user_id)->find();
        //共用参数
        $this->assign('merchant', $merchant);
        $this->assign('user', $user);
        $this->assign('car', $car);
        $this->assign('consume', $consume);
        $this->assign('other', $other);

        //电子资料附件（如何获取，名称，下载地址），是动态的
        $files = [];

        //有值才加载
        if ($files) {
            $this->assign('files', $files);
        }

        if ($user['user_type'] == User::USER_TYPE_PERSON) { //个人
            $bank = BankCard::where('user_id', '=', $user_id)->find();
            $bank['bank_code'] = config('bank_list.' . $bank['bank_code']); //银行信息

            $this->assign('bank', $bank);

            return view('Merchant/user_show');
        } elseif ($user['user_type'] == User::USER_TYPE_COMPANY) { //企业
            $company = UserCompany::where('user_id', '=', $user_id)->find();
            $company['bank_code'] = config('bank_list.' . $company['bank_code']); //银行信息

            $this->assign('company', $company);

            return view('Merchant/company_show');
        }
    }

    /**
     * 商户充值
     */
    public function recharge()
    {
        $url = input('url', 'Index/index');
        $param['money'] = input('money', 0);
        $param['user_id'] = $this->_Uid;
        //$param['return_url'] = 'http://' . $_SERVER['HTTP_HOST'] . url($url);//本地测试
        $param['return_url'] = config('current_url') . url($url);

        //调用接口都要用try catch
        try {
            $data = UserService::accountRecharge($param);
            if ($data['code'] == 0) {
                header("Location:" . $data['data']['redirect_url']);
                exit;
            } else {
                $this->error($data['msg']);
            }
        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }
    }
    
    /**
     * 商户提现
     */
    public function withdraw()
    {
        $url = input('url', 'Index/index');
        $param['money'] = input('money', 0);
        $param['user_id'] = $this->_Uid;
        //$param['return_url'] = 'http://' . $_SERVER['HTTP_HOST'] . url($url);//本地测试
        $param['return_url'] = config('current_url') . url($url);

        //调用接口都要用try catch
        try {
            $data = UserService::accountWithdraw($param);
            if ($data['code'] == 0) {
                header("Location:" . $data['data']['redirect_url']);
                exit;
            } else {
                $this->error($data['msg']);
            }
        } catch (\Exception $ex) {
            $this->error($ex->getMessage());
        }
    }

    /**
     * 资金明细
     * @return type
     */
    public function detail()
    {
        //搜索条件
        $category = input('category/d', 0);
        $status = input('status/d', 0);
        $start_time = input('start_time/s', '');
        $end_time = input('end_time/s', '');
        $this->assign('category', $category);
        $this->assign('status', $status);
        $this->assign('start_time', $start_time);
        $this->assign('end_time', $end_time);

        $where = ['user_id' => ['=', $this->_Uid]];

        //操作
        if ($category) {
            $where['category'] = ['=', $category];
        }
        //状态
        if ($status) {
            $where['status'] = ['=', $status];
        }

        //操作时间
        if ($start_time && $end_time) { //如果两个区间搜索都有值
            $where['add_time'] = ['between', [strtotime($start_time), strtotime($end_time) + 24 * 3600 - 1]];
        } elseif ($start_time) { //只有起始值
            $where['add_time'] = ['>=', strtotime($start_time)];
        } elseif ($end_time) { //只有结束值
            $where['add_time'] = ['<', strtotime($end_time) + 24 * 3600];
        }

        $page = input('page', 1); //页码
        $count = UserMoneyLog::where($where)->count();
        $list = UserMoneyLog::where($where)->page($page, Constant::PAGE_SIZE_MID)->select();

        foreach ($list as $key => $val) {
            $list[$key]['category'] = UserMoneyLog::getCategoryName($val['category']); //操作类型
            $list[$key]['status'] = UserMoneyLog::getStatusName($val['status']); //状态
            $list[$key]['affect_money'] = number_format($val['affect_money'], 2); //金额，千分位和小数点
        }

        //分页
        $page_class = new Page();
        $paginator = $page_class->pages($count, Constant::PAGE_SIZE_MID, $page);

        $this->assign('list', $list);
        $this->assign('paginator', $paginator);

        //操作列表
        $category_list = UserMoneyLog::getCategoryList();
        $this->assign('category_list', $category_list);

        //状态列表
        $status_list = UserMoneyLog::getStatusList();
        $this->assign('status_list', $status_list);

        return view('Merchant/detail');
    }

}
